package com.xayy.health.ds.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.kawins.base.result.CheckResult;
import cn.kawins.base.utils.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xayy.health.core.constant.TableNameConstant;
import com.xayy.health.core.enums.RunningStatusEnum;
import com.xayy.health.core.enums.SystemModelTypeEnum;
import com.xayy.health.core.enums.TaskInfoStatusEnum;
import com.xayy.health.ds.model.DsCalculateData;
import com.xayy.health.ds.model.DsTaskInfo;
import com.xayy.health.ds.service.*;
import com.xayy.health.mgt.model.vo.TaskVo;
import com.xtck.ha.common.core.domain.R;
import com.xtck.ha.common.core.web.service.dsimpl.BaseServiceImpl;
import com.xtck.ha.common.core.config.DsServerConfig;
import com.xtck.ha.common.core.utils.DomainUtils;
import com.xayy.health.ds.model.DsTaskChildInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description: DsTaskChildInfoService实现类
 * @Auther:liuyuan
 * @Date:2025-07-09
 */
@Slf4j
@Service
public class DsTaskChildInfoServiceImpl extends BaseServiceImpl<DsTaskChildInfo> implements DsTaskChildInfoService {
    @Autowired
    DsTaskInfoService dsTaskInfoService;
    @Autowired
    DsCalculateDataService dsCalculateDataService;
    @Autowired
    DsDiagnoseMultipleParametersDataService dsDiagnoseMultipleParametersDataService;
    @Autowired
    DsDiagnosePredictDataService dsDiagnosePredictDataService;
    @Autowired
    DsTyDataService dsTyDataService;
    @Autowired
    DsPhDataService dsPhDataService;
    @Autowired
    DsTcDataService dsTcDataService;
    @Autowired
    DsTaskParamInfoService dsTaskParamInfoService;
    @Autowired
    DsSelectTelemetryDataService dsSelectTelemetryDataService;
    /**
     * 冗余代码，为自定义开发DS-Server接口服务
     */
    private static String TABLE_NAME = "TB_TASK_CHILD_INFO";

    private String getUrl() {
        return getDsServerConfig().getUrl();
    }

    /**
     * 获取子任务信息根据开始时间
     *
     * @param taskInfo 入参
     * @return List<TaskChildInfo>
     */
    @Override
    public List<DsTaskChildInfo> selectTaskChildListByTime(DsTaskInfo taskInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
        String sql = "select * from HEALTH.tb_task_child_info where start_time >= " +
                "'" + sdf.format(taskInfo.getEndTime()) + "'\n" +
                " and (task_id = " +
                "'" + taskInfo.getId() + "'" +
                " or task_id is null);";
        return selectBySql(sql);
    }

    @Override
    public CheckResult<Object> updateStatusData(DsTaskInfo taskInfo) {
        List<Long> taskChildIds = null;
        //区分单参数和模型
        Integer isCaseOne = null;
        //区分是否是多参数
        Integer checkMultiparameter = null;
        //1长期运行2阶段性运行
        Integer runningStatus = null;
        //重启
        if (taskInfo.getStatus().equals(TaskInfoStatusEnum.RUNNING.getStatusCode())) {
            DsTaskInfo info =null;
            if (ObjectUtil.isNotNull(taskInfo.getId())) {
                info = dsTaskInfoService.selectTById(taskInfo.getId());
                List<DsTaskChildInfo> taskChildInfoList = selectTaskChildListByTime(info);
                if (CollUtil.isNotEmpty(taskChildInfoList)) {
                    taskChildIds = taskChildInfoList.stream().map(DsTaskChildInfo::getId).collect(Collectors.toList());
                }
                if (BeanUtil.isNotEmpty(info)) {
                    isCaseOne = info.getIsCaseOne();
                    checkMultiparameter = info.getCheckMultiparameter();
                    runningStatus = info.getRunningStatus();
                }
            }
            if (taskInfo.getType().equals(SystemModelTypeEnum.TREND_FORECASTING.getSystemModelTypeCode())) {
                CheckResult<DsTaskInfo> taskResult=dsTaskInfoService.selectTaskInfo(taskInfo.getId());
                if(null!=taskResult){
                    DsTaskInfo taskBaseInfo=taskResult.getData();
                    if(null!=taskBaseInfo){
                        //根据任务开始时间计算出任务结束时间
                        DateTime endTime= DateUtil.offsetMinute(taskInfo.getStartTime(), Integer.parseInt(taskBaseInfo.getCycle()));
                        taskInfo.setEndTime(endTime);
                        dsTaskInfoService.updateT(taskInfo);
                        if (1 == taskInfo.getStatus()) {
                            DsCalculateData delBody = DsCalculateData.builder()
                                    .taskId(taskInfo.getId())
                                    .sateCode(taskInfo.getSatelliteCode())
                                    .paramCode(taskInfo.getJsonParams())
                                    .build();
                            dsCalculateDataService.deleteTList(delBody);
                        }
                    }
                }
            } else if (taskInfo.getType().equals(SystemModelTypeEnum.POST_HOC_DIAGNOSIS.getSystemModelTypeCode())) {
                if (runningStatus.equals(RunningStatusEnum.LONG_RUNNING.getCode())) {
                    taskInfo.setLongRunningTime(taskInfo.getEndTime());
                }
                taskInfo.setDateEndTime(taskInfo.getEndTime());
                dsTaskInfoService.updateT(taskInfo);
                deleteTByIds(taskChildIds.toArray(new Long[0]));
                if (ObjectUtil.isNotNull(isCaseOne) || ObjectUtil.isNotNull(checkMultiparameter)) {
                    //双参数
                    if (checkMultiparameter.equals(1)) {
                        dsDiagnoseMultipleParametersDataService.deleteDiagnoseMultipleParametersData(taskChildIds);
                    } else {
                        //单参数
                        if (isCaseOne.equals(0)) {
                            if(null!=taskChildIds){
                                dsDiagnoseMultipleParametersDataService.deleteDiagnoseMultipleParametersData(taskChildIds);
                            }
                        } else {
                            //单参数模型
                            dsCalculateDataService.deleteCalculateDataByIds(taskChildIds);
                            dsDiagnosePredictDataService.deletePredictDataByIds(taskChildIds);
                        }
                    }
                }
            } else if (taskInfo.getType().equals(SystemModelTypeEnum.DATA_PROCESSING.getSystemModelTypeCode())) {
                dsTaskInfoService.updateT(taskInfo);
                if (CollUtil.isNotEmpty(taskChildIds)) {
                    deleteTByIds(taskChildIds.toArray(new Long[0]));
                    dsTyDataService.deleteTbTyData(taskChildIds);
                    dsPhDataService.deleteTbPhData(taskChildIds);
                    dsTcDataService.deleteTbTcData(taskChildIds);
                }
            }
        } else {
            //停止状态
            if (taskInfo.getType().equals(SystemModelTypeEnum.POST_HOC_DIAGNOSIS.getSystemModelTypeCode())) {
                taskInfo.setEndTime(DateUtil.date());
                dsTaskInfoService.updateT(taskInfo);
            } else {
                //0停止1启动
                dsTaskInfoService.updateT(taskInfo);
            }
        }
        return CheckResult.success("更新成功");
    }

    /**
     * 批量（单个）删除任务及其子任务
     *
     * @param taskVo 任务入参
     * @return ResultBody
     */
    @Override
    public CheckResult<Object> deleteChildTask(TaskVo taskVo) {
        // 批量删任务
        if (CollUtil.isNotEmpty(taskVo.getTaskId())) {
            // 防止脏数据
            dsTaskInfoService.updateBatchStatus(taskVo.getTaskId());
            List<Long> taskId = taskVo.getTaskId();
            List<DsTaskInfo> taskInfos = dsTaskInfoService.selectByIds(taskVo.getTaskId());
            //预测数据
            if (taskVo.getType() == 3) {
                List<Long> predictIdList = taskInfos.stream().filter(item -> item.getType().equals(SystemModelTypeEnum.TREND_FORECASTING.getSystemModelTypeCode())).map(DsTaskInfo::getId).collect(Collectors.toList());
                dsTaskInfoService.deleteCalculateData(predictIdList);
            }
            ArrayList<Long> idLongs = new ArrayList<>();
            for (Long aLong : taskId) {
                List<DsTaskChildInfo> taskChildInfos = selectTList(DsTaskChildInfo.builder().taskId(aLong).build());
                for (DsTaskChildInfo taskChildInfo : taskChildInfos) {
                    idLongs.add(taskChildInfo.getId());
                }
            }
            if (CollUtil.isNotEmpty(idLongs)) {
                dsTyDataService.deleteTbTyData(idLongs);
                dsTcDataService.deleteTbTcData(idLongs);
                dsPhDataService.deleteTbPhData(idLongs);
                if (taskVo.getType() == 2) {
                    dsDiagnoseMultipleParametersDataService.deleteDiagnoseMultipleParametersData(idLongs);
                }
                deleteTByIds(idLongs.toArray(new Long[0]));
            }
            dsTaskParamInfoService.deleteBatchParams(taskVo.getTaskId());
            dsTaskInfoService.deleteTByIds(taskVo.getTaskId().toArray(new Long[0]));
        }

        if (CollUtil.isNotEmpty(taskVo.getTaskChildId())) {
            // 批量删子任务
            List<Long> taskChildId = taskVo.getTaskChildId();
            updateByIds(taskChildId);
            dsTyDataService.deleteTbTyData(taskChildId);
            dsTcDataService.deleteTbTcData(taskChildId);
            dsPhDataService.deleteTbPhData(taskChildId);
            dsDiagnoseMultipleParametersDataService.deleteDiagnoseMultipleParametersData(taskVo.getTaskChildId());
            /*删除运行时保存的使用后的遥测数据*/
            taskChildId.forEach(item -> dsSelectTelemetryDataService.deleteTable(TableNameConstant.RUN_TASK_TELEMETRY + item));
        }
        return CheckResult.success("删除成功");
    }

    @Override
    /**
     * 更新子任务状态
     *
     * @param taskChildId 子任务id
     */
    public void updateByIds(List<Long> taskChildId){
        String sql="update HEALTH.tb_task_child_info set status = 4 where id in\n (";
        for (long id : taskChildId){
            sql += id+",";
        }
        if (sql.endsWith(",")) {
            sql = sql.substring(0, sql.length() - 1);
        }
        sql += ");";
        selectBySql(sql);
    }

}
